#include "srv_head.h"

/**
 * do_put_cmd - 对上传文件命令功能进行处理函数
 * @sockfd: 连接到客户端的socket文件描述符
 * @cmd: 执行的命令字符串
 *
*/
void do_cli_put(int cli_fd, char *Cmd)
{
	char filename[N];
	int ret;
	char buffer[N];
	int fd;
	int nbytes;
	//获取文件名  Cmd
	bzero(filename, N);
	strncpy(filename, Cmd,strlen(Cmd));
	printf("上传的文件名: %s\n", filename);
	write(cli_fd, "ok\n", N);
	//等待判断文件是否存在

	ret = read(cli_fd, buffer, N);
	if(ret < 0){
		perror("read");
		exit(1);
	}
	if(!strncmp(buffer, "error", 5)){
		printf("文件%s不存在\n",filename);
		return ;
	}
	if(!strncmp(buffer, "success", 7)){
		printf("文件 %s 存在\n", filename);;
		}
	write(cli_fd, "ok\n", N);//接收上传
	
	fd = open(filename, O_WRONLY|O_CREAT|O_TRUNC, 0644);
	if(fd < 0){
		perror("open");
		exit(1);
	}

	bzero(buffer,N);
//接收数据
	while ((nbytes = read (cli_fd, buffer,N))>0){
		printf("nbytes=%d\n",nbytes);
		ret = write(fd, buffer, nbytes);
		if(ret < 0){
			perror("write");
			close(fd);
			exit(1);
		}
		bzero(buffer,N);
		}
	printf("put filename %s success\n\n", filename);
	printf("文件上传成功\n");
	close(fd);	
	close(cli_fd);
	printf("do cli put\n");

}


